package com.demo.controller;

import com.demo.model.FormsInfo;
import com.demo.model.JsonMessage;
import com.demo.model.PartnerStat;
import com.demo.service.PartnerStatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Api(value = "伙伴录入查询接口")
@RequestMapping("/admin/stat")
public class PartnerStatController {

    @Autowired
    private PartnerStatService statService;

    //根据时间段查询用户信息
    @ApiOperation(value = "根据时间段查询用户信息")
    @RequestMapping("list")
    public JsonMessage list(@DateTimeFormat(pattern = "yyyy-MM-dd") Date begin,
                            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(end);
        calendar.add(Calendar.DATE, 1);
        end = calendar.getTime();
        List<PartnerStat> list = statService.stat(begin, end);
        JsonMessage msg = new JsonMessage();
        msg.setData(list);
        return msg;
    }


    @ApiOperation(value = "导出用户信息")
    @RequestMapping("export")
    public ResponseEntity<byte[]> export(@DateTimeFormat(pattern = "yyyy-MM-dd") Date begin,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        //create excel object
        int days=Calendar.DAY_OF_WEEK;
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date datse=new Date();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(datse);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(datse);
        calendar2.add(Calendar.DAY_OF_MONTH, -days+1);
        String ben=simpleDateFormat.format(calendar2.getTime());
        calendar1.add(Calendar.DAY_OF_MONTH,-days+8);
        String ends=simpleDateFormat.format(calendar1.getTime());


        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(end);
        calendar.add(Calendar.DATE, 1);
        end = calendar.getTime();

        XSSFSheet sheet1 = hssfWorkbook.createSheet("Sheet1");
        XSSFSheet sheet2 = hssfWorkbook.createSheet("Sheet2");

        //sheet1
        List<PartnerStat> list1 = statService.stat(begin, end);
        String[] headerList1 = {"序号", "姓名", "部门", "资产伙伴", "资金伙伴", "司法伙伴", "政府伙伴", "退出伙伴", "同业伙伴", "总计"};
        XSSFRow row = sheet1.createRow(0);
        for (int i = 0; i < headerList1.length; i++) {
            row.createCell(i).setCellValue(headerList1[i]);
        }
        int i = 0;
        for (PartnerStat stat : list1) {
            int j = 0;
            XSSFRow row1 = sheet1.createRow(++i);
            row1.createCell(j++).setCellValue(i);
            row1.createCell(j++).setCellValue(stat.getTrueName());
            row1.createCell(j++).setCellValue(stat.getDepName());
            row1.createCell(j++).setCellValue(stat.getAssetNum());
            row1.createCell(j++).setCellValue(stat.getFundNum());
            row1.createCell(j++).setCellValue(stat.getJusticeNum());
            row1.createCell(j++).setCellValue(stat.getOrgNum());
            row1.createCell(j++).setCellValue(stat.getExitNum());
            row1.createCell(j++).setCellValue(stat.getPeerNum());
            row1.createCell(j++).setCellValue(stat.getAssetNum() + stat.getFundNum()
                    + stat.getJusticeNum() + stat.getOrgNum() + stat.getExitNum() + stat.getPeerNum());
        }
        //sheet2

        List<FormsInfo> all = statService.all();
        Map<String, FormsInfo> alls = new HashMap<>();
        for (FormsInfo s : all
        ) {
            alls.put(s.getUserId(), s);
        }




        List<FormsInfo> week = statService.week(ben, ends);
        Map<String, Integer> w = new HashMap<>();
        for (FormsInfo ws : week
        ) {
            w.put(ws.getUserId(), ws.getWeek());
        }
        List<FormsInfo> month = statService.month();
        Map<String, Integer> m = new HashMap<>();
        for (FormsInfo ms : month
        ) {
            m.put(ms.getUserId(), ms.getMonth());
        }
        List<FormsInfo> quarter = statService.quarter();
        Map<String, Integer> q = new HashMap<>();
        for (FormsInfo qs : quarter
        ) {
            q.put(qs.getUserId(), qs.getQuarter());
        }
        List<FormsInfo> year = statService.year();
        Map<String, Integer> y = new HashMap<>();
        for (FormsInfo ys : year
        ) {
            y.put(ys.getUserId(), ys.getYear());
        }
        List<FormsInfo> allClient = statService.allClient();
        Map<String, Integer> cli = new HashMap<>();
        for (FormsInfo a : allClient
        ) {
            cli.put(a.getUserId(), a.getAllClient());
        }
        List<FormsInfo> allInfo = statService.allInfo();
        Map<String, Integer> alinfo = new HashMap<>();
        for (FormsInfo als : allInfo
        ) {
            alinfo.put(als.getUserId(), als.getAllInfo());
        }


        for (FormsInfo a : all
        ) {

            a.setWeek(w.get(a.getUserId()));
            a.setMonth(m.get(a.getUserId()));
            a.setQuarter(q.get(a.getUserId()));
            a.setYear(y.get(a.getUserId()));
            a.setAllClient(cli.get(a.getUserId()));
            a.setAllInfo(alinfo.get(a.getUserId()));
        }

        List<String> listall = new ArrayList<>();
        for (FormsInfo a : all
        ) {
            listall.add(a.getDepId());
        }
        //查询所有部门id
        List<FormsInfo> list = statService.depId();
        for (FormsInfo p : list
        ) {
            //把缺失的部门添加到all
            if (listall.contains(p.getDepId()) == false) {
                FormsInfo miss = new FormsInfo();
                miss.setDepId(p.getDepId());
                miss.setDepName(p.getDepName());
                miss.setTrueName("");
                all.add(miss);
            }
        }

        int countWeek = 0, countMonth = 0, countQuarter = 0, countYear = 0;
        int aClient = 0, aInfo = 0;


        List<FormsInfo> min = new ArrayList<>();
        String name = "";
        String depID = "";
        for (int j = 0; j < list.size(); j++) {
            for (int p = 0; p < all.size(); p++
            ) {
                //累计相同部门id的人数
                if (list.get(j).getDepId().equals(all.get(p).getDepId())
                ) {
                    name = all.get(p).getDepName();
                    depID = all.get(p).getDepId();
                    countWeek += all.get(p).getWeek();
                    countMonth += all.get(p).getMonth();
                    countQuarter += all.get(p).getQuarter();
                    countYear += all.get(p).getYear();
                    aClient += all.get(p).getAllClient();
                    aInfo += all.get(p).getAllInfo();
                }
            }
            min.add(new FormsInfo(depID, name + "小计", countWeek, countMonth, countQuarter, countYear, aClient, aInfo));
            countWeek = 0;
            countMonth = 0;
            countQuarter = 0;
            countYear = 0;

            aClient = 0;
            aInfo = 0;

        }
        all.addAll(min);

        //添加之后的部门进行排序
        Collections.sort(all, new Comparator<FormsInfo>() {
            @Override
            public int compare(FormsInfo o1, FormsInfo o2) {
                return o1.getDepId().compareTo(o2.getDepId());
            }
        });

        //获取所有小计的下标
        List<Integer> quickColumn = new ArrayList<>();
        quickColumn.add(0);
        int top = 0;
        for (int s = 0; s < all.size(); s++) {

            if (all.get(s).getTrueName().indexOf("小计") != -1) {
                top = s + 1;
                quickColumn.add(top);
            }
        }

        String[] hels2 = {"序号", "部门", "姓名", "录入客户数", "", "", "", "客户质量", ""};
        XSSFRow row3 = sheet2.createRow(0);
        for (int j = 0; j < hels2.length; j++) {
            row3.createCell(j).setCellValue(hels2[j]);
        }
        String[] headerList2 = {"序号", "部门", "姓名", "本周新增", "本月累计", "本季度累积",
                "年度累计", "录入伙伴数量", "录入客户数量"};
        XSSFRow row2 = sheet2.createRow(1);
        for (int a = 0; a < headerList2.length; a++) {
            row2.createCell(a).setCellValue(headerList2[a]);
        }

        hssfWorkbook.createCellStyle();

        //合并单元格
        sheet2.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
        sheet2.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
        sheet2.addMergedRegion(new CellRangeAddress(0, 1, 2, 2));
        sheet2.addMergedRegion(new CellRangeAddress(0, 0, 3, 6));
        sheet2.addMergedRegion(new CellRangeAddress(0, 0, 7, 8));
        //设置列宽
        sheet2.setColumnWidth(1, 15 * 256);
        for (int j = 2; j < headerList2.length; j++) {
            sheet2.setColumnWidth(j, 13 * 256);
        }


        int b = 1;
        int k = 0;
        int cell = 0;

        for (int a = 0; a < all.size(); a++) {
            int j = 0;

            XSSFRow row1 = sheet2.createRow(++b);
            cell++;
            row1.createCell(j++).setCellValue(cell);

            if (all.get(a).getTrueName().indexOf("小计") != -1) {
                sheet2.addMergedRegion(new CellRangeAddress(quickColumn.get(k) + 2, quickColumn.get(k + 1) + 1, 1, 1));
                k++;
            }
            row1.createCell(j++).setCellValue(all.get(a).getDepName());
            row1.createCell(j++).setCellValue(all.get(a).getTrueName());
            row1.createCell(j++).setCellValue(all.get(a).getWeek());
            row1.createCell(j++).setCellValue(all.get(a).getMonth());
            row1.createCell(j++).setCellValue(all.get(a).getQuarter());
            row1.createCell(j++).setCellValue(all.get(a).getYear());
            row1.createCell(j++).setCellValue(all.get(a).getAllInfo());
            row1.createCell(j++).setCellValue(all.get(a).getAllClient());
        }


        try {
            hssfWorkbook.write(os);
            hssfWorkbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        // headers.add("Content-Type", "application/octet-stream;charset=utf-8");
        headers.add("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
        headers.add("Connection", "close");
        headers.add("Accept-Ranges", "bytes");
        headers.add("Access-Control-Expose-Headers", "Content-Disposition");
        String myFileName = URLEncoder.encode("汇总.xlsx", Charset.forName("utf-8"));
        headers.add("Content-Disposition", "attachment;filename=" + myFileName);
        //   + new String( "汇总.xlsx".getBytes(Charset.forName("UTF-8")), Charset.forName("ISO-8859-1")));
        return ResponseEntity
                .ok()
                .headers(headers)
                //.contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(os.toByteArray());
    }


}
